import request from '../utils/request.ts'
import {type CommonResDTO, toJSON, updateToken, updateUid} from './config.ts'

export interface UserSignupReqDTO {
    account: string
    password: string
}

export interface UserSigninResDTO {
    id: string
    account: string
    username: string
    token: string // jwt
}

// 游客获取Token
export async function userAnonymous(): Promise<CommonResDTO<UserSigninResDTO>>{
    const resp = await request.get('/user/anonymous')
    return resolveSigninResp(resp)
}

// 游客刷新Token
export async function refreshUserAnonymous(id: string): Promise<CommonResDTO<UserSigninResDTO>>{
    const resp = await request.get(`/user/anonymous/$${id}`)
    return resolveSigninResp(resp)
}

// 用户注册
// export async function userSignup(data: UserSignupReqDTO): Promise<CommonResDTO<UserSigninResDTO>> {
//     data.password = signPwd(data.password)
//     const resp = await request.post('/user/signup', data)
//     return resolveSigninResp(resp)
// }

// 用户登录
// export async function userSignin(data: UserSignupReqDTO): Promise<CommonResDTO<UserSigninResDTO>> {
//     data.password = signPwd(data.password)
//     const resp = await request.post('/user/signin', data)
//     return resolveSigninResp(resp)
// }

// function signPwd(pwd: string): string {
//     return sm3(pwd, {
//         key: import.meta.env.USER_PWD_KEY,
//     })
// }

function resolveSigninResp(resp: any): CommonResDTO<UserSigninResDTO> {
    const result = toJSON<CommonResDTO<UserSigninResDTO>>(resp)
    if (result.code === 0 && result.data) {
        updateToken(result.data.token)
        updateUid(result.data.id)
    }
    return result
}